package com.wnhoo.smartfishtank.ble;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.contants.Config;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class BleService extends Service {
    private final String TAG = "BleService";

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private Handler mHandler = new Handler();
    public  Map<String, BluetoothGatt> mMapBleGatt;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 8000;
    public static final String ACTION_DEV_FOUND = "com.fb.ble.action.device_found";
    public static final String ACTION_DEV_SCANNING = "com.fb.ble.action.device_scanning";
    public static final String ACTION_DEV_STOP_SCAN = "com.fb.ble.action.device_stop_scan";
    public static final String ACTION_DEV_CONNECTED = "com.fb.ble.action.device_connected";
    public static final String ACTION_DEV_DISCONNECTED = "com.fb.ble.action.device_disconnected";
    public static final String ACTION_DEV_GATT_SERVICE_DISCOVERED = "com.fb.ble.action.device_gatt_services_discovered";

    //
    public static final String ACTION_DEV_FIND = "com.fb.ble.action.find_waring";// 寻找报警的广播
    public static final String ACTION_DEV_ANTILOSS = "com.fb.ble.action.antiloss_waring";// 防丢报警的广播
    public static final String ACTION_DEV_WARING_STOP = "com.fb.ble.action.waring_stop";// 停止报警的广播
    public static final String ACTION_DEV_AUDIO_RECORD = "com.fb.ble.action.audio_record";// 录音的广播
    public static final String ACTION_DEV_AUDIO_RECORD_CHANGE = "com.fb.ble.action.audio_record_change";// 录音设置改变的广播

    public final static String NORMAL_START = "com.fb.ble.action.normal_start";
    public final static String ACTION_DEV_LOST = "com.fb.ble.action.device_lost";

    public static final String ACTION_DEV_SINGLE_CLICK = "com.fb.ble.action.device_single_click";// 单机的指令
    private boolean isPreviousCommandHandling = false;// 是否在处理前一条指令中
    /**
     * 固定名称
     */
    private String filterName = "WIM";
    ;
//	private String filterName="TCM BT313287";;
    /**
     * 通知重启蓝牙
     */
    public static final String ACTION_RESTART_BLE = "com.calm.ble.action_restart_ble";
    public static final String ACTION_RESTART_BLE1 = "com.calm.ble.action_restart_ble1";
    /**
     * 定时扫描发现设备
     */
    public static final String ACTION_TIMING_DEV_FOUND = "com.fb.ble.action.device_timing_found";
    /**
     * 广播移除丢失列表
     */
    public static final String ACTION_LOST_REMOVE = "com.fb.ble.action.action_lost_remove";
    /**
     * 广播设备丢失
     */
    public static final String ACTION_DEV_ADD_LOST = "com.calm.ble.action_dev_add_lost";
    /**
     * 广播报警距离变化
     */
    public static final String ACTION_ALARM_DIS_CHANGE = "con.calm.ble.action_alarm_dis_change";
    public static int mRssiThresholdMeter = 10;// 超过多少范围开始报警,
    public static int mRssiThreshold = (int) (-4.00 * (float) (mRssiThresholdMeter) - 48.82 - 8);
    public float r;

    public BluetoothGatt getBluetoothGatt(String address){

        return mMapBleGatt.get(address);
    }
    /**
     * 录音相关
     */
    private File mRecordFile;
    private MediaRecorder mMediaRecorder;
    private BroadcastReceiver mAudioRecordBrostReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_DEV_AUDIO_RECORD)) {// 录音或者停止录音
                if (mRecordFile == null) {// 没有录音，开始录音
                    File dirRecord = new File(Config.DIR_AUTIO_RECODER);
                    if (!dirRecord.exists()) {
                        if (!dirRecord.mkdirs()) {
                            return;
                        }
                    }
                    mRecordFile = new File(dirRecord, UUID.randomUUID().toString().replace("-", "") + ".amr");
                    mRecordFile.setLastModified(System.currentTimeMillis());
                    mMediaRecorder = new MediaRecorder();
                    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                    mMediaRecorder.setOutputFile(mRecordFile.getAbsolutePath());
                    try {
                        mMediaRecorder.prepare();
                        mMediaRecorder.start();
//						Toast.makeText(BleService.this, getResources().getString(R.string.start_recording), Toast.LENGTH_LONG).show();
                    } catch (IllegalStateException e) {
                        mMediaRecorder.stop();
                        mMediaRecorder.release();
                        mMediaRecorder = null;
                        mRecordFile = null;
                        e.printStackTrace();
                    } catch (IOException e) {
                        mMediaRecorder.stop();
                        mMediaRecorder.release();
                        mMediaRecorder = null;
                        mRecordFile = null;
                        e.printStackTrace();
                    }
                } else {
                    if (mMediaRecorder != null) {
                        mMediaRecorder.stop();
                        mMediaRecorder.release();
                        mMediaRecorder = null;
                        mRecordFile = null;
//						Toast.makeText(BleService.this, getResources().getString(R.string.end_recording), Toast.LENGTH_LONG).show();
                    }
                }
            } else if (action.equals(ACTION_DEV_AUDIO_RECORD_CHANGE)) {
                if (mRecordFile != null) {
                    if (mMediaRecorder != null) {
                        mMediaRecorder.stop();
                        mMediaRecorder.release();
                        mMediaRecorder = null;
                        mRecordFile = null;
//						Toast.makeText(BleService.this, getResources().getString(R.string.end_recording), Toast.LENGTH_LONG).show();
                    }
                }
            } else if (action.equals(ACTION_ALARM_DIS_CHANGE)) {
//				mRssiThresholdMeter = SettingSp.getInstance(BleService.this).getAlarmDis();
//				mRssiThreshold = (int) (-4.00 * (float) (mRssiThresholdMeter) - 48.82 - 8);
            }
        }
    };
    private String tag = "BleService";

    /**
     * 2014-06-29加入
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mRssiHandler.sendEmptyMessage(0x1);
        mMapBleGatt = new HashMap<String, BluetoothGatt>();
        IntentFilter filter = new IntentFilter(ACTION_DEV_AUDIO_RECORD);
        filter.addAction(ACTION_DEV_AUDIO_RECORD_CHANGE);
        filter.addAction(ACTION_ALARM_DIS_CHANGE);
        registerReceiver(mAudioRecordBrostReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mAudioRecordBrostReceiver);
        close();
    }

    private Handler mCommandHanler = new Handler();

//     private boolean mServiceRestarted=false;
//
//     @Override
//     public int onStartCommand(Intent intent, int flags, int startId) {
//     Log.d(TAG, "onStartCommand()");
//     if(intent != null) {
//     if(intent.getAction().equals(NORMAL_START)) {
//     Log.d(TAG, "BluetoothFereService started by activity");
//     mServiceRestarted = false;
//     }
//     } else {//自己重启的Service
//     Log.d(TAG, "BluetoothFereService restarted by ifself");
//     mServiceRestarted = true;
//     initialize();
//     scanLeDevice(true);
//     }
//     return START_STICKY;
//     }

    private final BleServiceBinder mBinder = new BleServiceBinder();

    public class BleServiceBinder extends Binder {
        public BleService getService() {
            return BleService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    @SuppressLint("NewApi")
    public boolean initialize() {
        // For API level 18 and above, get a reference to BluetoothAdapter
        // through
        // BluetoothManager.
        if (mBluetoothManager == null) {
            mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            if (mBluetoothManager == null) {
                return false;
            }
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            return false;
        }
        return true;
    }

    /**
     * After using a given BLE device, the app must call this method to ensure
     * resources are released properly.
     */
    public void close() {
        Set<String> keySet = mMapBleGatt.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            BluetoothGatt gatt = mMapBleGatt.get(key);
            if (gatt != null) {
                gatt.close();
            }
        }
        mMapBleGatt.clear();
    }
    /**
     * After using a given BLE device, the app must call this method to ensure
     * resources are released properly.
     */
    public void disConnect() {
        Set<String> keySet = mMapBleGatt.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            BluetoothGatt gatt = mMapBleGatt.get(key);
            if (gatt != null) {
                gatt.disconnect();
            }
        }
    }

    // 关闭某个device
    public void closeDevice(String address) {
        BluetoothGatt gatt = mMapBleGatt.get(address);
        if (gatt != null) {
            gatt.close();
        }
        mMapBleGatt.remove(address);
    }

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action, String deviceAddress) {
        final Intent intent = new Intent(action);
        intent.putExtra("device_address", deviceAddress);
        sendBroadcast(intent);
    }

    private void broadcastUpdate(final String action, String deviceAddress, String name) {
        final Intent intent = new Intent(action);
        intent.putExtra("device_address", deviceAddress);
        intent.putExtra("device_name", name);
        sendBroadcast(intent);
    }

//    /**
//     * 定时扫描设置
//     *
//     * @param enable
//     */
//    public void scanTimingDevice(final boolean enable) {
//        if (enable) {
//            // Stops scanning after a pre-defined scan period.
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    mBluetoothAdapter.stopLeScan(mTimingLeScanCallback);
//                }
//            }, 8000); //每次扫描2秒
//            mBluetoothAdapter.startLeScan(mTimingLeScanCallback);
//        } else {
//            mBluetoothAdapter.stopLeScan(mTimingLeScanCallback);
//        }
//    }
//
//    private BluetoothAdapter.LeScanCallback mTimingLeScanCallback = new BluetoothAdapter.LeScanCallback() {
//
//        @Override
//        public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
//            // if(mServiceRestarted == false) {
//            // 发现设备，查找数据库是否已经存在
//            String address = device.getAddress();
//            String deviceName = device.getName();
//
////			mScan(address, deviceName);
//            mScan_filter(address, deviceName);
//        }
//
//
//        // BLE操作
//        public void scanLeDevice(final boolean enable) {
//            if (enable) {
//                // Stops scanning after a pre-defined scan period.
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
//                        broadcastUpdate(ACTION_DEV_STOP_SCAN);
//                    }
//                }, SCAN_PERIOD);
//                mBluetoothAdapter.startLeScan(mLeScanCallback);
//                broadcastUpdate(ACTION_DEV_SCANNING);
//            } else {
//                mBluetoothAdapter.stopLeScan(mLeScanCallback);
//                broadcastUpdate(ACTION_DEV_STOP_SCAN);
//            }
//        }
//
//        // Device scan callback.
//        private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
//            @Override
//            public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
//                // if(mServiceRestarted == false) {
//                // 发现设备，查找数据库是否已经存zai
//                Log.i(TAG, "device" + device.getAddress() + device.getName());
//                String address = device.getAddress();
//                String deviceName = device.getName();
//
////			mLeScan(address, deviceName);
//                mLeScan_filter(address, deviceName);//过滤设备,显示固定名字  TCM BT313287
//            }


    public void connAll() {
        Set<String> keySet = mMapBleGatt.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            connect(key);
        }
    }

    /**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     * @return Return true if the connection is initiated successfully. The
     * connection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     * callback.
     */
    public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            return false;
        }
        BluetoothGatt gatt = mMapBleGatt.get(address);
        if (gatt != null) {
            gatt.close();
        }
        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            return false;
        }
        // We want to directly connect to the device, so we are setting the
        // autoConnect
        // parameter to false.
        gatt = device.connectGatt(this, false, new GattCallback());
//		gatt.beginReliableWrite();
        mMapBleGatt.put(address, gatt);
        Log.i(tag, "mMapBleGatt.size()" + mMapBleGatt.size());
        return true;
    }

    public void disconnect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            return;
        }
        BluetoothGatt gatt = mMapBleGatt.get(address);
        if (gatt != null) {
            gatt.disconnect();
        }
    }
    public class GattCallback extends BluetoothGattCallback {

        @Override
        public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) {
            Log.i(tag,"onConnectionStateChange"+status+":"+newState);
//            closeDevice(gatt.getDevice().getAddress());
            if (mMapBleGatt.get(gatt.getDevice().getAddress()) != gatt) {
                broadcastUpdate(ACTION_RESTART_BLE);
                return;
            }

            if (newState == BluetoothProfile.STATE_CONNECTED) {
                broadcastUpdate(ACTION_DEV_CONNECTED, gatt.getDevice().getAddress());
                // Attempts to discover services after successful connection.
                gatt.discoverServices();
                // 连接成功，重置这个设备的Rssi值缓存
                Rssi rssi = mRssiMaps.get(gatt.getDevice().getAddress());
                if (rssi != null) {
                    rssi.reset();
                } else {
                    mRssiMaps.put(gatt.getDevice().getAddress(), new Rssi());
                }
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
//                gatt.connect();
                broadcastUpdate(ACTION_DEV_DISCONNECTED, gatt.getDevice().getAddress());
                enablePeerDeviceNotifyMe(gatt, false);
            }

        }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.i(tag,"onServicesDiscovered"+status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // saveGattServicesAndChara(gatt.getServices());
//                broadcastUpdate(ACTION_DEV_GATT_SERVICE_DISCOVERED, gatt.getDevice().getAddress());
                enablePeerDeviceNotifyMe(gatt, true);
                UUID serviceUUID = BleGattAttributes.UUID_IMMIDIATE_ALERT_SERVICEL;
                UUID characteristicUUID = BleGattAttributes.UUID_ALERT_LEVEL_CHARACTERISTIC;
                BluetoothGattCharacteristic characteristic = getCharacteristic(gatt.getDevice().getAddress(), serviceUUID, characteristicUUID);
                gatt.readCharacteristic(characteristic);
            } else {

            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);

            }
        }

        @Override
        public void onCharacteristicChanged(final BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            // broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            byte[] remoteKeyValue;
            remoteKeyValue = characteristic.getValue();
            if (remoteKeyValue[0] == 1) {
                if (isPreviousCommandHandling) {// 代表双击的第二次
                    Log.i("CALM", "ACTION_DEV_DOUBLE_CLICK---------");
                    mCommandHanler.removeCallbacksAndMessages(null);// 清除上一条指令
                    isPreviousCommandHandling = false;
                    broadcastUpdate(ACTION_DEV_FIND, gatt.getDevice().getAddress());
                } else {
                    isPreviousCommandHandling = true;
                    mCommandHanler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            isPreviousCommandHandling = false;
                            broadcastUpdate(ACTION_DEV_SINGLE_CLICK, gatt.getDevice().getAddress(), gatt.getDevice().getName());
                            Log.i("CALM", "ACTION_DEV_SINGLE_CLICK-------------------");
                        }
                    }, 500);
                }
            }
        }
        private  double ENVIRONMENT_ATTENUATION_FACTOR = 2.76;
        private  int A = -55;
        private  double distance;
        @Override
        public void onReadRemoteRssi(final BluetoothGatt gatt, int rssi, int status) {
            int iRssi = Math.abs(rssi);
            float power = (float) ((iRssi-55)/(10*ENVIRONMENT_ATTENUATION_FACTOR));
            Log.i(TAG, "rssiSum ----------------:" + rssi);
            Log.i(TAG, "distance ----------------:" + Math.pow(10, power));
            distance = Math.pow(10, power);
            if(distance>=LMAPP.dataPlug.getDistance()){
                broadcastUpdate(ACTION_DEV_ANTILOSS, gatt.getDevice().getAddress());
            }
            Rssi rssiObj = mRssiMaps.get(gatt.getDevice().getAddress());
            if (rssiObj != null) {
                if (rssiObj.needVerification()) {
                    boolean waring = rssiObj.verification();
                    if (waring) {
                        // 通知界面在防丢设备
                        broadcastUpdate(ACTION_DEV_ANTILOSS, gatt.getDevice().getAddress());
                    }
                } else {
                    rssiObj.add(rssi);
                }
            } else {
                mRssiMaps.put(gatt.getDevice().getAddress(), new Rssi());
            }
        }
    }
    // 开启接受设备发送的点击指令
    public void enablePeerDeviceNotifyMe(BluetoothGatt gatt, boolean enable) {
        UUID serviceUUID = BleGattAttributes.UUID_FINDME_SERVICE;
        UUID characteristicUUID = BleGattAttributes.UUID_FIND_ME_CHARACTERISTIC;
        BluetoothGattCharacteristic characteristic = getCharacteristic(gatt, serviceUUID, characteristicUUID);
        if (characteristic != null) {
            final int charaProp = characteristic.getProperties();
            if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                setCharacteristicNotification(gatt, characteristic, enable);
            }
        }
    }

    /*
     * 发送报警指令 //0 停止报警 //1 报警不闪灯 //2 报警闪灯
     */
    public void findPeerDevice(byte waringCommand, final String address) {
        if (waringCommand != 0 && waringCommand != 1 && waringCommand != 2) {// 错误的指令
            return;
        }
        UUID serviceUUID = BleGattAttributes.UUID_IMMIDIATE_ALERT_SERVICEL;
        UUID characteristicUUID = BleGattAttributes.UUID_ALERT_LEVEL_CHARACTERISTIC;
        BluetoothGattCharacteristic characteristic = getCharacteristic(address, serviceUUID, characteristicUUID);
        if (characteristic == null) {
            return;
        }
        final int charaProp = characteristic.getProperties();
        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
            byte value[] = {waringCommand};
            characteristic.setValue(value);
            mMapBleGatt.get(address).writeCharacteristic(characteristic);
        }
    }

    /**
     * Enables or disables notification on a give characteristic.
     *
     * @param characteristic Characteristic to act on.
     * @param enabled        If true, enable notification. False otherwise.
     */
    private void setCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, boolean enabled) {
        gatt.setCharacteristicNotification(characteristic, enabled);

        // TODO 下面这个是干叼的
        if (BleGattAttributes.UUID_FIND_ME_CHARACTERISTIC.equals(characteristic.getUuid())) {
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        }

    }

    // 获取某个特定设备的某个服务下的某个特征值
    private BluetoothGattCharacteristic getCharacteristic(String address, UUID serviceUUID, UUID characteristicUUID) {
        BluetoothGatt gatt = mMapBleGatt.get(address);
        return getCharacteristic(gatt, serviceUUID, characteristicUUID);
    }

    // 获取某个特定设备的某个服务下的某个特征值
    private BluetoothGattCharacteristic getCharacteristic(BluetoothGatt gatt, UUID serviceUUID, UUID characteristicUUID) {
        if (gatt == null) {
            return null;
        }
        BluetoothGattService gattService = gatt.getService(serviceUUID);
        if (gattService == null) {
            return null;
        }
        BluetoothGattCharacteristic gattCharacteristic = gattService.getCharacteristic(characteristicUUID);
        if (gattCharacteristic == null) {
            return null;
        }
        return gattCharacteristic;
    }

    // 关于蓝牙Rssi距离报警的代码
    public Map<String, Rssi> mRssiMaps = new HashMap<String, Rssi>();
    public Handler mRssiHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0x1) {
                mDisconnectGattAddress.clear();
                for (String key : mRssiMaps.keySet()) {
                    updateRssi(key);
                }
                for (String address : mDisconnectGattAddress) {
                    mRssiMaps.remove(address);
                }
                mRssiHandler.sendEmptyMessageDelayed(0x1, 100);
            }
        }
    };

    private List<String> mDisconnectGattAddress = new ArrayList<String>();

    class Rssi {
        //private static final int mRssiThresholdMeter = 10;// 超过多少范围开始报警
        //private static final int mRssiThreshold = (int) (-4.00 * (float) (mRssiThresholdMeter) - 48.82 - 8);

        public Rssi() {
//			mRssiThresholdMeter = SettingSp.getInstance(BleService.this).getAlarmDis();
            mRssiThreshold = (int) (-4.00 * (float) (mRssiThresholdMeter) - 48.82 - 8);
        }

        private static final int MAX_GRAND_TOTAL = 20;// 最大累计数
        private int current_index = 0;
        private int[] rssi = new int[MAX_GRAND_TOTAL];

        public boolean needVerification() {// 是否需要开始验证
            if (current_index >= MAX_GRAND_TOTAL) {
                return true;
            }
            return false;
        }

//		public boolean verification() {// 是否超出范围
//			Arrays.sort(rssi);
//			int rssiSum = 0;
//			for (int i = 2; i < MAX_GRAND_TOTAL - 2; i++) {
//				rssiSum = rssiSum + rssi[i];
//			}
//			reset();
//			int rssiReal = rssiSum / (MAX_GRAND_TOTAL - 4);
//			if (rssiReal < mRssiThreshold) {// 当信号比阀值要低，表示距离远了
//				return true;
//			} else {
//				return false;
//			}
//
//		}


        public boolean verification() {// 是否超出范围

            Arrays.sort(rssi);
            int rssiSum = 0;
            for (int i = 3; i < MAX_GRAND_TOTAL - 6; i++) {
                rssiSum = rssiSum + rssi[i];
            }
            reset();

//            Log.i(TAG, "rssiSum ----------------:" + rssiSum);

            int rssiReal = rssiSum / (MAX_GRAND_TOTAL - 4);


//            Log.i(TAG, "r ----------------:" + r);
//            Log.i(TAG, "rssiReal----------->:" + rssiReal);
//            Log.i(TAG, "mRssiThreshold------------------>:" + mRssiThreshold);

            if (rssiReal < mRssiThreshold) {// 当信号比阀值要低，表示距离远了
                return true;
            } else {
                return false;
            }

        }


        public void add(int value) {
            if (current_index >= MAX_GRAND_TOTAL) {
                return;
            }
            rssi[current_index] = value;
            current_index++;
        }

        public void reset() {
            current_index = 0;
            for (int i = 0; i < rssi.length; i++) {
                rssi[i] = 0;
            }
        }
    }

    private void updateRssi(final String deviceAddress) {
        final BluetoothGatt gatt = mMapBleGatt.get(deviceAddress);
        if (gatt != null) {
            BluetoothDevice device = gatt.getDevice();
            int connectState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT_SERVER);
            if (connectState == BluetoothProfile.STATE_CONNECTED) {
                mRssiHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        gatt.readRemoteRssi();
                    }
                }, 100);
            } else {
                mDisconnectGattAddress.add(deviceAddress);
            }
        }
    }
}
